package com.zklh.leetcode.interviewTop150;

import java.util.HashMap;
import java.util.Map;

/**
 * 单词规律算法实现
 */
public class Solution290 {
    public boolean wordPattern(String pattern, String s) {
        Map<Character, String> charToWord = new HashMap<>();
        Map<String, Character> wordToChar = new HashMap<>();
        String[] words = s.split(" ");
        if (pattern.length() != words.length) {
            return false;
        }
        for (int i = 0; i < pattern.length(); i++) {
            if (!charToWord.containsKey(pattern.charAt(i))) {
                if (wordToChar.containsKey(words[i])) {
                    return false;
                }
                charToWord.put(pattern.charAt(i), words[i]);
                wordToChar.put(words[i], pattern.charAt(i));
            } else {
                if (!charToWord.get(pattern.charAt(i)).equals(words[i])) {
                    return false;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Solution290 solution = new Solution290();
        System.out.println(solution.wordPattern("abba", "dog cat cat dog"));
    }
}
